<?php

namespace App\Http\Controllers\V1;

use App\Http\Controllers\ApiBaseController;
use App\Http\Requests\CzProductRequest;
use App\Models\CzProduct;
use App\Models\CzSpec;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;


class CzProductController extends ApiBaseController
{

    public function index(Request $request)
    {
        $paginator = CzProduct::filter($request->all())->with([
            'specs',
            'province' => function ($query) {
                $query->select('id', 'short_name');
            },
            'city' => function ($query) {
                $query->select('id', 'short_name');
            },
        ])->orderBy('id', 'desc')->paginate($this->pageSize);
        return success(page_format($paginator));
    }

    public function listAll()
    {
        $items = CzProduct::all();
        return success(['data' => $items]);
    }

    public function show(Request $request, CzProduct $model)
    {
        $id = $request->get('id');
        $data = $model->with('specs')->find($id);
        return success(['data' => $data->toArray()]);
    }

    public function create(CzProductRequest $request)
    {
        $params = $request->all();
        DB::transaction(function () use ($params) {
            $params['province_id'] = $params['province_id'] ?? 0;
            $params['city_id'] = $params['city_id'] ?? 0;

            $model = CzProduct::create($params);
            $product_id = $model->id;
            $specs = $params['specs'];
            if (count($specs) > 0) {
                foreach ($specs as $item) {
                    $is_exist = DB::table('cz_spec')->where('spec_code', trim($item['spec_code']))->first();
                    if ($is_exist) {
                        throw new HttpResponseException(error("[{$item['spec_code']}]产品编码已存在"));
                    }
                    $tmp_add = [
                        'product_id' => $product_id,
                        'face_value' => $item['face_value'],
                        'market_price' => floatval($item['market_price']),
                        'sell_price' => floatval($item['sell_price']),
                        'spec_code' => trim($item['spec_code']),
                        'status' => intval($item['status']),
                        'is_cache' => intval($item['is_cache']),
                        'is_auto' => intval($item['is_auto']),
                        // 'is_limit' => intval($item['is_limit']),
                    ];
                    // if ($tmp_add['is_limit'] == 1) {
                    //     //开启限充记录开始时间
                    //     $tmp_add['limit_time'] = time();
                    // }
                    CzSpec::create($tmp_add);
                }
            }
        });
        return success([], '添加成功');
    }

    public function update(CzProductRequest $request, CzProduct $model)
    {
        $id = $request->post('id');
        $product = $model->find($id);
        $params = $request->all();
        if ($product) {
            DB::transaction(function () use ($product, $params) {
                $params['province_id'] = $params['province_id'] ?? 0;
                $params['city_id'] = $params['city_id'] ?? 0;

                $product->update($params);
                $product_id = $product->id;
                $specs = $params['specs'];
                if (count($specs) > 0) {
                    foreach ($specs as $item) {
                        $spec_id = $item['id'] ?? 0;
                        $is_exist = DB::table('cz_spec')->where('spec_code', trim($item['spec_code']))->first();
                        if ($is_exist && $is_exist->id != $spec_id) {
                            throw new HttpResponseException(error("[{$item['spec_code']}]产品编码已存在"));
                        }

                        $tmp_add = [
                            'product_id' => $product_id,
                            'face_value' => $item['face_value'],
                            'market_price' => floatval($item['market_price']),
                            'sell_price' => floatval($item['sell_price']),
                            'spec_code' => trim($item['spec_code']),
                            'status' => intval($item['status']),
                            'is_cache' => intval($item['is_cache']),
                            'is_auto' => intval($item['is_auto']),
                            // 'is_limit' => intval($item['is_limit']),
                            // 'limit_time' => time(),

                        ];

                        if (isset($item['id']) && $item['id'] > 0) {
                            $info = CzSpec::where('product_id', $product_id)->find($item['id']);
                            // if ($tmp_add['is_limit'] == 1 && $info->is_limit == 0) {
                            //     //从关闭限充到开启限充记录开始时间
                            //     $tmp_add['limit_time'] = time();
                            // }
                            // 手动重置限充开始时间
                            // if ($item['is_re_limit_time'] == 1) {
                            //     $tmp_add['limit_time'] = time();
                            // }
                            $info->update($tmp_add);
                        } else {
                            // if ($tmp_add['is_limit'] == 1) {
                            //     //开启限充记录开始时间
                            //     $tmp_add['limit_time'] = time();
                            // }
                            CzSpec::create($tmp_add);
                        }
                    }
                }
            });
        } else {
            return error('数据不存在');
        }

        return success([], '更新成功');
    }

    public function destroy($ids, Request $request, CzProduct $model)
    {
        $id_arr = explode(',', $ids);
        DB::transaction(function () use ($model, $id_arr) {
            $model->destroy($id_arr);
            CzSpec::whereIn('product_id', $id_arr)->delete();
        });
        return success([], '删除成功');
    }

    public function listSpec(Request $request)
    {
        $paginator = CzSpec::filter($request->all())->with([
            'product'
        ])->orderBy('id', 'desc')->paginate($this->pageSize);
        return success(page_format($paginator));
    }
    public function listAllSpec(Request $request)
    {
        $items = CzSpec::filter($request->all())->with([
            'product' => function ($query) {
                $query->select('id', 'title');
            },
        ])->select('id', 'product_id', 'face_value')->orderBy('product_id', 'desc')->get();
        return success([
            'data' => $items
        ], '获取成功');
    }
    public function changeSplit(Request $request, CzProduct $model)
    {
        $id = $request->post('id');
        $is_split = $request->post('is_split');
        $product = $model->find($id);
        if (!$product) {
            return error('数据不存在');
        }
        $product->update([
            'is_split' => $is_split
        ]);
        return success([], '更新成功');
    }

    public function changeStatus(Request $request, CzProduct $model)
    {
        $params = $request->all();
        $id = $request->post('id');
        $status = $request->post('status');

        $product = $model->find($id);
        if (!$product) {
            return error('数据不存在');
        }
        $product->update([
            'status' => $status
        ]);
        return success([], '更新成功');
    }
    public function changeStopFail(Request $request, CzProduct $model)
    {
        $params = $request->all();
        $id = $request->post('id');
        $status = $request->post('status');

        $product = $model->find($id);
        if (!$product) {
            return error('数据不存在');
        }
        $product->update([
            'stop_fail' => $status
        ]);
        return success([], '更新成功');
    }

    public function setTimeOut(Request $request, CzProduct $model)
    {
        $id = $request->post('id');
        $timeout = $request->post('timeout', '0');

        $product = $model->find($id);
        if (!$product) {
            return error('数据不存在');
        }
        $product->update([
            'timeout' => $timeout ?? 0
        ]);
        return success([], '更新成功');
    }
}
